// web/src/app/(employee)/company-side/new-employee/_components/employee-name-form.tsx
'use client';
import React, {useState} from 'react';
import {Company, City, Hr, Education, Tag, Employee} from "@prisma/client";
import * as z from "zod";
import {useRouter} from "next/navigation";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import toast from "react-hot-toast";
import {Button} from "@mantine/core";
import {Form, FormControl, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {createEmployee} from "@/app/(employee)/company-side/new-employee/actions/create-employee";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import Editor from "@/components/learn/editor";
import {updateEmployee} from "@/app/(employee)/company-side/edit-employee/actions/update-employee";


const formSchema = z.object({
    name: z.string().min(1, {
        message: 'Name is required',
    }),
    description: z.string().min(1, {
        message: 'Description is required',
    }),
    salary: z.coerce.number(),
    tags: z.string().min(1, {
        message: 'Tags is required',
    }),
    educationId: z.string().min(1, {
        message: 'Education is required',
    }),
    cityId: z.string().min(1, {
        message: 'City is required',
    }),
})

const UpdateEmployeeForm = ({hr, cities, educations, employee}: {
    hr: Hr & { company: Company };
    cities: City[],
    educations: Education[],
    employee: Employee & { tags: Tag[] }
}) => {
    const router = useRouter()

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            name: employee.name,
            description: employee.description,
            educationId: employee.educationId!,
            cityId: employee.cityId,
            tags: employee.tags.map(t => (t.name)).join(','),
            salary: employee.salary
        }
    })

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            await updateEmployee({
                ...values,
                salary: parseFloat(values.salary.toString()),
                hrId: hr.id,
                companyId: hr.company.id,
                id: employee.id
            })
            toast.success(`更新成功`)
            router.replace(`/company-side/`)
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    return (
        <div className={`mx-24 my-6 border rounded-md p-4`}>
            <Form {...form}>
                <form
                    onSubmit={form.handleSubmit(() => {
                        onSubmit(form.getValues())
                    })}
                    className="space-y-6"
                >
                    <div className={`space-y-4`}>
                        <>
                            <FormField
                                control={form.control}
                                name="name"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>职位名称</FormLabel>
                                        <FormControl>
                                            <Input
                                                {...field}
                                                placeholder="比如: 数据采集员"
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name={'description'}
                                render={({field}) => (
                                    <FormItem className="w-full">
                                        <FormLabel>职位描述</FormLabel>
                                        <FormControl>
                                            <Editor
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="salary"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>Salary</FormLabel>
                                        <FormControl>
                                            <Input
                                                step={1}
                                                type={'number'}
                                                {...field}
                                                placeholder="月薪"
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="tags"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>Tags</FormLabel>
                                        <FormControl>
                                            <Input
                                                {...field}
                                                placeholder="岗位标签, 如五险一金(多个用,隔开)"
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="educationId"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>学历要求</FormLabel>
                                        <Select
                                            onValueChange={field.onChange}
                                            defaultValue={field.value}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={'Select a role'}/>
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {educations.map(e => (
                                                    <SelectItem value={e.id} key={e.id}>
                                                        {e.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="cityId"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>城市</FormLabel>
                                        <Select
                                            onValueChange={field.onChange}
                                            defaultValue={field.value}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={'Select a role'}/>
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {cities.map(e => (
                                                    <SelectItem value={e.id} key={e.id}>
                                                        {e.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                        </>
                    </div>
                    <Button
                        type="submit"
                        className={`w-full`}
                    >
                        Save
                    </Button>
                </form>
            </Form>
        </div>
    );
};

export default UpdateEmployeeForm;